/**************************************************************
  > File Name: sendShmget.c
  > Author: LuoLiang
  > Mail: 1204553475@qq.com 
  > Created Time: 2022年02月23日 星期三 03时16分19秒
 **************************************************************/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <semaphore.h>
#include <sys/wait.h>
#include "sem.h"

int main(int argc, char **argv)
{
	key_t key;
	sem_t *semp = NULL;
	sem_t *semp1 = NULL;
	int shmid;
	size_t size = 4096;
	char *shmp = NULL;
	char buf[BUFSIZE] = {0};
	int fd;

	key = ftok(PATHNAME, PROCID);
	if (key < 0)
	{
		perror("ftok()");
		exit(1);
	}
	
	shmid = shmget(key, size, IPC_CREAT | 0666);
	if (shmid < 0)
	{
		perror("shmget()");
		exit(1);
	}
	
	shmp = shmat(shmid, NULL, 0);
	if (shmp == NULL)
	{
		perror("shmat()");
		exit(1);
	}
	
	fd = open(argv[1], O_WRONLY);
	if (fd < 0)
	{
		perror("open()");
		exit(1);
	}

	semp = sem_open(SEMPATH, O_CREAT, 0664, 1);
	if (semp == SEM_FAILED)
	{
		perror("sem_open()");
		exit(1);
	}

	semp1 = sem_open(SEMPATH1, O_CREAT, 0664, 1);
	if (semp1 == SEM_FAILED)
	{
		perror("sem_open()");
		exit(1);
	}


	sem_wait(semp1);	
	int len;
	while (1)
	{
		sem_wait(semp1);	
		strcpy(buf, shmp);
		sem_post(semp);
		len = strlen(buf);
		write(fd, buf, len);
		memset(buf, 0, BUFSIZE);
		memset(shmp, 0, size);
		if (len < BUFSIZE)
			break;
	}
	
	sem_close(semp);
	sem_close(semp1);
	sem_unlink(SEMPATH);
	sem_unlink(SEMPATH1);
	
	close(fd);
	shmdt(shmp);
    exit(0);
}
